﻿using System;
using System.Collections.Generic;

namespace Cache.FileCache
{
    /// <summary>
    /// 文件缓存工具类
    /// </summary>
    public static class FileCacheClient
    {
        private static readonly Dictionary<string, FileCache> instances = new Dictionary<string, FileCache>();
        private static FileCache defaultInstance;

        public static void Setup(string name, string fileCachePath)
        {
            if (instances.ContainsKey(name))
            {
                throw new Exception("Trying to configure FileCachedClient instance \"" + name + "\" twice.");
            }
            instances[name] = new FileCache(fileCachePath);
        }

        public static FileCache GetInstance()
        {
            return defaultInstance ?? (defaultInstance = GetInstance("Default"));
        }

        public static FileCache GetInstance(string name)
        {
            FileCache c;
            if (instances.TryGetValue(name, out c))
            {
                return c;
            }
            else
            {
                FileCachedConfig config = FileCachedSection.GetConfig();

                if (config != null && config.Nodes.ContainsKey(name))
                {
                    Setup(name, config.Nodes[name].FileCachePath);
                    c = GetInstance(name);
                    c.IsCache = config.IsCache;
                    //c.KeyPrefix = config.Nodes[name].KeyPrefix;
                    c.CacheSubDirs = config.Nodes[name].CacheSubDirs;
                    return c;
                }
                throw new Exception("Unable to find FileCachedClient instance \"" + name + "\".");
            }
        }
    }
}